#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) Huoty, All rights reserved
# Author: Huoty <sudohuoty@163.com>
# CreateTime: 2020-06-09 08:31:37


class InviteCodeChecker(object):

    @classmethod
    def _get_char_num_mapping(cls):
        """生成字符与数字的映射表"""
        if not hasattr(cls, "_char_num_mapping"):
            string = __import__("string")
            chars = string.ascii_lowercase
            mapping = {
                c: n
                for i in range(0, len(chars), 9)
                for c, n in zip(chars[i:(i + 9)], range(1, 10))
            }
            mapping.update({c: int(c) for c in string.digits})
            cls._char_num_mapping = mapping
        return cls._char_num_mapping

    def _check(self, code):
        char_table = self._get_char_num_mapping()
        print(char_table)
        print(code[-1::-2], [char_table[c] for c in code[-1::-2]])
        print(code[-2::-2], [char_table[c] for c in code[-2::-2]])
        odd_sum = sum(char_table[c] for c in code[-1::-2])

        def calc_even_pos(c):
            n = char_table[c]
            n *= 2
            if n > 9:
                n -= 9
            return n

        even_sum = sum(calc_even_pos(c) for c in code[-2::-2])

        if (odd_sum + even_sum) % 10 == 0:
            return "ok"
        else:
            return "error"

    def __call__(self, code):
        if len(code) != 16:
            raise Exception("invalid code: '{}'".format(code))

        try:
            return self._check(code)
        except KeyError:
            # 如果邀请码中包含除小写字母和数字以外的字符则抛出异常
            raise Exception("invalid code: '{}'".format(code))


check_invite_code = InviteCodeChecker()
code = "g0e8izzadf0xb7xo"
print(check_invite_code(code))
